文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. 问题描述
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
1 | Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) |
2. 求解
方法一
先求解两个链表的和,直接一个链表结束或两个链表同时结束,然后再处理没结束链表的剩下部分。
1 | public class Solution { |
方法二
方法一中的代码有较多的冗余,例如current.next = new ListNode(sum % 10);
出现了两次,两次while循环的逻辑是非常类似的,经过代码的变换可以将两部分合成一部分,即同时处理两个链表直至两个链表都结束。
1 | public class Solution { |